// 测本约车全局通知  上车 下车 取消发车按钮事件执行
import {
	add
} from '@/api/crud.js'
let WebIM = require("@/utils/WebIM")["default"];
const disp = require("@/utils/broadcast");
import {
	mapGetters
} from 'vuex'
export default {
	computed: {
		...mapGetters(['loginForm', 'disable']),
		uid() {
			return this.loginForm.uid;
		},
		//信用分低于60分，抢车计时5秒，低于40分8秒，低于20分10秒，0分不准抢车
		carTimeMax() {
			const {
				creditScore
			} = this.loginForm
			if (creditScore >= 60) return 3
			if (creditScore >= 40 && creditScore < 60) return 5
			if (creditScore >= 20 && creditScore < 40) return 8
			if (creditScore < 20) return 10
			return 1
		}
	},
	data() {
		return {
			cancelCar: '开放上车后取消发车将会记录毁车次数，确定取消吗？', //发行取消发车提示
			storeCancelCar: '若发车前1小时内下车会影响你的信用分哦！', //门店下车提示
			confirmCar: '正在抢车...',
			modelFlag: false,
			closeModalTips: '',
			activeItem: {},
			confirmCarTime: 3,
			modelType: '',
			initBusFlag: false,
			intoCarLoading: false,
			outCarLoading: false
		}
	},
	created() {
		this.initBus()
		this.confirmCarTime = this.carTimeMax;
	},
	destroyed() {
		uni.$off('busNotice')
		uni.$off('cancelCar')
		uni.$off('startCar')
	},
	onShow() {
		this.initCarBus()
	},
	methods: {
		initCarBus() {
			this.initBusFlag && this.initBus()
			this.initBusFlag = true;
		},
		initBus() {
			if (!this.uid) return false;
			uni.$on('busNotice', newValue => {
				if (newValue.customEvent === 'gather_game_tips') return false;
				const {
					driveCarId
				} = newValue
				let groupItem = null;
				if (this.tabs) {
					groupItem = this.$refs.mescroll[this.tabIndex].dataList.find(val => val.id == driveCarId)
				}
				if (this.dataList) groupItem = this.dataList.find(val => val.id == driveCarId)
				if (this.item && this.item.id == driveCarId) groupItem = this.item;
				// if (groupItem) {
				// 	this.$set(groupItem, 'participate', newValue.userSmallDtos.length)
				// 	this.$set(groupItem, 'userSmallDtos', newValue.userSmallDtos)
				// 	const flag = newValue.userSmallDtos.some(val => val.uid == this.uid);
				// 	this.$set(groupItem, 'isIntoCar', flag)
				// }
				if(newValue.userSmallIds&&groupItem){
					const userSmallIds = newValue.userSmallIds.split(',')
					this.$set(groupItem, 'participate', userSmallIds.length)
					// this.$set(groupItem, 'userSmallDtos', newValue.userSmallDtos)
					//更新用户数据
					this.getDetail&&this.getDetail() //页面上有这个方法才会执行 获取测本约车详情
					const flag = userSmallIds.some(val => val == this.uid);
					this.$set(groupItem, 'isIntoCar', flag)
				}
			})
			uni.$on('cancelCar', res => {
				console.log('cancelCar')
				if (res.customEvent === 'gather_game_tips') return false;
				this.cancelCarcallback && this.cancelCarcallback(res)
			})
			uni.$on('startCar', res => {
				console.log('startCar')
				if (res.customEvent === 'gather_game_tips') return false;
				this.startCarcallback && this.startCarcallback(res)
			})
			disp.fire("em.chat.readyNum");
		},
		//邀请店家
		shareStore(item) {
			this.$u.route({
				url: '/pages/shareCar/shareCar',
				params: {
					hxGroupId: item.hxChatGroupId,
					id: item.id,
					productId: item.productId,
					name: item.name,
					createName: item.createName
				}
			})
		},
		//全局上车统一管理
		async pushCar(type, item) {
			if (!this.uid) {
				this.loginFlagFn()
				return false;
			}
			const creditScore = this.loginForm.creditScore
			if (creditScore == 0) {
				this.$u.toast('信用分太低了，不准上车了！')
				return false;
			}
			try {
				await this.isBillVaildate() //是否验票
				await this.exhibitValidate() //是否设置参展信息
				this.modelFlag = true;
				this.activeItem = item;
				this.modelType = type;
				this.closeModalTips = this[type];
				this.timeDown()
			} catch (e) {
				console.log(e)
				//TODO handle the exception
			}
		},
		loginFlagFn() {
			this.modelFlag = true;
			this.modelType = 'loginFlag';
			this.closeModalTips = '请先登录才能上车哦';
		},
		//清空倒计时状态
		clearTime() {
			if (this.modelType === 'confirmCar') {
				if (this.downTimer) clearTimeout(this.downTimer);
				this.confirmCarTime = this.carTimeMax;
				this.downTimer = null;
				this.closeModalTips = '正在抢车...';
				this.modelType = ''
			}
		},
		timeDown() {
			this.closeModalTips = `正在抢车...${this.confirmCarTime}s`
			this.downTimer = setTimeout(async () => {
				if (this.confirmCarTime == 1) {
					try {
						await this.confirmCarFn(this.activeItem)
						this.clearTime()
						this.$u.toast('上车成功，已加入群聊');
						disp.fire("em.chat.readyNum");
						setTimeout(() => {
							this.intoCar && this.intoCar(this.activeItem) //上车回调
						}, 1000)
					} catch (e) {
						if (this.downTimer) clearTimeout(this.downTimer);
						this.confirmCarTime = this.carTimeMax;
						this.downTimer = null;
					}
					return false;
				}
				--this.confirmCarTime;
				this.timeDown()
			}, 1000);
		},
		async confirmCarFn(item) {
			try {
				this.intoCarLoading = true;
				await add({
					singleData: this.$store.getters.loginForm.uid + '',
					showLoading: true,
					type: 'single' //不是对象
				}, 'driveCar', 'shopApi', `into/${item.id}`)
				this.modelFlag = false;
				this.intoCarLoading = false;
				return Promise.resolve()
			} catch (e) {
				//TODO handle the exception
				console.log(e)
				uni.hideToast();
				this.closeModalTips = e.message || '太多人啦，没挤上！'
				this.modelType = 'rejectFlag'
				this.intoCarLoading = false;
				return Promise.reject(e)
			}
		},
		//下车或取消发车
		async closeCar(type, item) {
			try {
				await this.isBillVaildate()
				await this.exhibitValidate()
				this.closeModalTips = this[type];
				this.modelFlag = true;
				this.modelType = '';
				this.activeItem = item;
			} catch (e) {
				//TODO handle the exception
			}
		},
		confirmClose() {
			if (this.modelType === 'rejectFlag') {
				this.modelFlag = false;
				return false;
			}
			if (this.modelType === 'loginFlag') {
				this.modelFlag = false;
				this.$u.route({
					url: "/pagesB/register/register"
				})
				return false;
			}
			if (this.modelType === 'cancelCarFlag') {
				this.$u.route({
					type: 'back'
				})
				return false;
			}
			if (this.modelType === 'startCarFlag') {
				this.$u.route({
					type: 'relaunch',
					url: "/page/carTime/carTime",
					params: {
						id: this.item.id
					}
				})
				return false;
			}
			this.outCarLoading = true
			const isCreater = this.loginForm.uid !== this.activeItem.creatorId
			const urlName = isCreater ? 'outOff' : 'cancelCar';
			add(this.loginForm.uid + '', 'driveCar', this.apiModule, urlName + '/' + this.activeItem.id).then(res => {
				this.outCarLoading = false
				if (isCreater) {
					this.$u.toast('下车成功，已退出群聊');
					//如果是下车
					const key = `${this.activeItem.hxGroupId}${this.$store.getters.loginForm.hxUsername}`
					const historyChatMsgKeys = `rendered_${key}`;
					console.log(historyChatMsgKeys)
					uni.removeStorageSync(historyChatMsgKeys)
					uni.removeStorageSync(key)
					this.isCreater && this.outCar() //下车回调
					disp.fire("em.chat.readyNum");
				} else {
					this.cancelCarcallback && this.cancelCarcallback(this.activeItem) //取消发车回调
				}
			}).catch(() => {
				this.outCarLoading = false
			})
		}
	}
}
